﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Client.Managers
{
    class CronManager
    {
        string[] ggSymbols = new string[0]; //普通的个股symbol
        string[] indexSymbols = new string[0]; //指数symbol
        LinkedList<string> monitoredSymbols = new LinkedList<string>();//监控股票的symbol

        public DataCenter.Models.StockInfo[] ggStocks { get; private set; }
        public DataCenter.Models.StockInfo[] indexStocks { get; private set; }
        public DataCenter.Models.StockInfo[] monitoredStocks { get; private set; }  //存储获取到的监控股票信息

        public bool cronType { get; private set; }
        int biaoji = 0;
        int cyclePeriod = 5000;


        public event Func<Task<int>> beginCron;
        public event Action updateSuccessfully;
        public event Func<Task<int>> updateSuccessfullyAsync;
        public event Action firstUpdateSuccessfully;

        public CronManager()
        {
            ggStocks = new DataCenter.Models.StockInfo[0];
            indexStocks = new DataCenter.Models.StockInfo[0];
            monitoredStocks = new DataCenter.Models.StockInfo[0];

            UpdateIndexSymbols(new string[] { "sh000001", "sz399001", "sz399006" });
        }


        public void UpdateGGSymbol(string[] symbols)
        {
            ggSymbols = symbols;
        }
        public void ClearGGSymbols()
        {
            ggSymbols = new string[0];
        }

        public void UpdateIndexSymbols(string[] symbols)
        {
            indexSymbols = symbols;
        }
        public void ClearIndexSymbols()
        {
            indexSymbols = new string[0];
        }

        public bool AddMonitoredSymbol(string symbol)
        {
            bool a = false;
            foreach(var i in this.monitoredSymbols)
            {
                if (i == symbol)
                {
                    a = true;
                    break;
                }
            }
            if (!a)
            {
                this.monitoredSymbols.AddFirst(symbol);
                return true;
            }
            return false;
        }
        public bool RemoveMonitoredSymbol(string symbol)
        {
            return monitoredSymbols.Remove(symbol);
        }
        public void ClearMonitoredSymbols()
        {
            monitoredSymbols.Clear();
        }

        public void ClearAll()
        {
            ClearGGSymbols();
            ClearIndexSymbols();
            ClearMonitoredSymbols();
        }

        public async void StartCron(bool start)
        {
            cronType = start;
            biaoji += 1;
            int bj = biaoji;

            if (start)
            {
                if (await LoopTask() == -1)
                {
                    Utility.ShowLoginAgain();
                    return;
                }
                firstUpdateSuccessfully?.Invoke();
            }

            while (cronType && biaoji==bj)
            {
                await Task.Delay(cyclePeriod);
                if (await LoopTask() == -1)
                {
                    Utility.ShowLoginAgain();
                    return;
                }
            }
        }

        private async Task<int> LoopTask()
        {
            try
            {
                if (beginCron != null)
                    await beginCron.Invoke();
                await UpdateData();
                if (updateSuccessfullyAsync != null)
                    await updateSuccessfullyAsync.Invoke();
                updateSuccessfully?.Invoke();
            }
            catch(DataCenter.MyException.APIReturnException e)
            {
                var l = e.Message.Split('~');
                if (l[0] == "1000")
                    return -1;
                throw;
            }
            
            return 0;
        }

        private async Task<int> UpdateData()
        {
            if (ggSymbols.Length == 0 && indexSymbols.Length == 0 && monitoredSymbols.Count == 0)
                return -1;

            //保存当前股票symbol各数组的长度，方便从接收的数据中获取对应数据。因为很可能在获取数据的过程中各股票数组已经改变
            int ggL = ggSymbols.Length;
            int indexL = indexSymbols.Length;
            int monitoredL = monitoredSymbols.Count;

            string[] l = new string[ggL + indexL + monitoredL];
            Array.Copy(ggSymbols, 0, l, 0, ggL);
            Array.Copy(indexSymbols, 0, l, ggL, indexL);
            Array.Copy(monitoredSymbols.ToArray(), 0, l, ggL + indexL, monitoredL);

            if (l.Length != 0)
            {
                var stockRes = await DataCenter.DataCenter.GetSSSJ(l);
                ggStocks = new DataCenter.Models.StockInfo[ggL];
                indexStocks = new DataCenter.Models.StockInfo[indexL];
                monitoredStocks = new DataCenter.Models.StockInfo[monitoredL];

                Array.Copy(stockRes, 0, ggStocks, 0, ggL);
                Array.Copy(stockRes, ggL, indexStocks, 0, indexL);
                Array.Copy(stockRes, ggL + indexL, monitoredStocks, 0, monitoredL);
            }

            //if (bkSymbol != DataCenter.Enums.BKType.non)
            //{
            //    bkRanking = await DataCenter.DataCenter.GetBKRanking(bkSymbol,1);
            //}
            
            return 0;
        }

    }
}
